<template>
  <div>
    <el-container style="height: 900px; border: 1px solid #eee">
      <el-header style="font-size: 40px; background-color: rgb(238, 241, 246)">
        <div class="header-left">
          <span>书缘校园-校园二手书交流系统</span>
        </div>
        <div class="header-right">
          <router-link to="/mySetting">
            <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
          </router-link>
        </div>
      </el-header>
      <el-container>
        <aside-layout></aside-layout>
        <el-main>
          <!-- 书籍状态统计 -->
          <el-row :gutter="20" style="margin-bottom: 20px;">
            <el-col :span="6">
              <el-card>
                <div class="stat-item">
                  <span class="stat-label">总书籍数量</span>
                  <span class="stat-value">{{ totalBooks }}</span>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card>
                <div class="stat-item">
                  <span class="stat-label">可售书籍</span>
                  <span class="stat-value">{{ availableBooks }}</span>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card>
                <div class="stat-item">
                  <span class="stat-label">已售出书籍</span>
                  <span class="stat-value">{{ soldBooks }}</span>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 搜索框和筛选 -->
          <el-row :gutter="20" style="margin-bottom: 20px;">
            <el-col :span="8">
              <el-input v-model="searchQuery" placeholder="请输入书名" clearable @clear="fetchBooks">
                <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
              </el-input>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="dialogVisible = true">上传书籍</el-button>
            </el-col>
          </el-row>

          <!-- 书籍列表 -->
          <el-table :data="filteredBooks"
            style="width: 100%; border-radius: 8px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);"
            @row-click="handleRowClick" :row-style="{ cursor: 'pointer' }"
            :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 'bold' }"
            :cell-style="{ padding: '12px 8px' }" :row-class-name="tableRowClassName">
            <el-table-column prop="BookName" label="书名" width="200"></el-table-column>
            <el-table-column prop="description" label="简介" width="350"></el-table-column>
            <el-table-column prop="price" label="价格" width="120"></el-table-column>
            <el-table-column prop="STATUS" label="状态" width="120">
              <template slot-scope="scope">
                <el-select v-model="scope.row.STATUS" placeholder="请选择状态" @change="handleStatusChange(scope.row)">
                  <el-option label="可售" value="可售"></el-option>
                  <el-option label="已售出" value="已售出"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="totalBooks"
            style="margin-top: 20px;"></el-pagination>

          <!-- 书籍详情弹窗 -->
          <el-dialog title="书籍详情" :visible.sync="detailDialogVisible" width="50%">
            <div v-if="selectedBook">
              <h3 style="margin-top: 10px;">{{ selectedBook.BookName }}</h3>
              <p style="color: #666;">{{ selectedBook.description }}</p>
              <p style="color: #e74c3c;">价格: {{ selectedBook.price }}元</p>
              <p style="color: #333;">状态:
                <el-tag :type="selectedBook.STATUS === '可售' ? 'success' : 'danger'">{{ selectedBook.STATUS }}</el-tag>
              </p>

              <!-- 编辑书籍信息 -->
              <el-form :model="selectedBook" label-width="80px" style="margin-top: 20px;">
                <el-form-item label="书名">
                  <el-input v-model="selectedBook.BookName"></el-input>
                </el-form-item>
                <el-form-item label="简介">
                  <el-input type="textarea" v-model="selectedBook.description"></el-input>
                </el-form-item>
                <el-form-item label="价格">
                  <el-input v-model="selectedBook.price"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="selectedBook.STATUS" placeholder="请选择状态" style="width: 100%;">
                    <el-option label="可售" value="可售"></el-option>
                    <el-option label="已售出" value="已售出"></el-option>
                  </el-select>
                </el-form-item>
              </el-form>

              <!-- 操作按钮 -->
              <div style="margin-top: 20px;">
                <el-button type="danger" @click="handleOffShelf(selectedBook)">下架</el-button>
                <el-button type="primary" @click="handleChangePrice(selectedBook)">更改价格</el-button>
              </div>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="detailDialogVisible = false">关闭</el-button>
              <el-button type="primary" @click="saveBookChanges">保存</el-button>
            </span>
          </el-dialog>

          <!-- 推荐书籍 -->
          <div style="margin-top: 40px;">
            <h2 style="color: #333;">推荐书籍</h2>
            <el-row :gutter="20">
              <el-col v-for="book in recommendedBooks" :key="book.id" :span="6">
                <el-card :body-style="{ padding: '20px' }" @click="openBookDetails(book)"
                  style="border-radius: 10px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);">
                  <img :src="book.cover" class="book-cover" />
                  <div class="book-info">
                    <h3 style="font-size: 18px; color: #333;">{{ book.name }}</h3>
                    <p style="color: #e74c3c;">价格: {{ book.price }}元</p>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>

          <!-- 上传书籍弹窗 -->
          <el-dialog title="上传书籍" :visible.sync="dialogVisible" width="40%">
            <el-form :model="bookForm" label-width="80px">
              <el-form-item label="书名">
                <el-input v-model="bookForm.BookName"></el-input>
              </el-form-item>
              <el-form-item label="简介">
                <el-input type="textarea" v-model="bookForm.description"></el-input>
              </el-form-item>
              <el-form-item label="价格">
                <el-input v-model="bookForm.price"></el-input>
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="bookForm.STATUS" placeholder="请选择状态" style="width: 100%;">
                  <el-option label="可售" value="可售"></el-option>
                  <el-option label="已售出" value="已售出"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="handleUpload">确 定</el-button>
            </span>
          </el-dialog>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import axios from 'axios'; // 引入 axios
import AsideLayout from '../../layout/AsideLayout.vue';

export default {
  components: { AsideLayout },
  data() {
    return {
      searchQuery: '', // 搜索框内容
      selectedCategory: '', // 选择的分类
      sortBy: '', // 排序方式
      tableData: [], // 书籍列表数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的条数
      totalBooks: 0, // 总书籍数量
      availableBooks: 0, // 可售书籍数量
      soldBooks: 0, // 已售出书籍数量
      dialogVisible: false, // 上传书籍弹窗的显示状态
      detailDialogVisible: false, // 书籍详情弹窗的显示状态
      selectedBook: null, // 当前选中的书籍
      bookForm: {
        BookName: '', // 书名
        description: '', // 简介
        price: '', // 价格
        STATUS: '可售', // 状态
      },
      recommendedBooks: [], // 推荐书籍
      operationLogs: [] // 操作记录
    };
  },
  computed: {
    // 根据搜索、分类和排序过滤书籍
    filteredBooks() {
      let books = this.tableData;

      // 搜索过滤
      if (this.searchQuery) {
        books = books.filter(book => book.BookName.includes(this.searchQuery) || book.description.includes(this.searchQuery));
      }

      // 排序
      if (this.sortBy === 'priceAsc') {
        books = books.sort((a, b) => a.price - b.price);
      } else if (this.sortBy === 'priceDesc') {
        books = books.sort((a, b) => b.price - a.price);
      } else if (this.sortBy === 'nameAsc') {
        books = books.sort((a, b) => a.BookName.localeCompare(b.BookName));
      } else if (this.sortBy === 'nameDesc') {
        books = books.sort((a, b) => b.BookName.localeCompare(a.BookName));
      }

      return books;
    }
  },
  methods: {
    // 获取书籍列表
    async fetchBooks() {
      try {
        // 获取书籍列表
        const response = await axios.get('http://localhost:3000/api/sell-books', {
          params: {
            query: this.searchQuery,
            page: this.currentPage,
            size: this.pageSize,
          },
        });

        this.tableData = response.data.sellBooks;
        this.totalBooks = response.data.total;
        this.availableBooks = this.tableData.filter(book => book.STATUS === '可售').length;
        this.soldBooks = this.tableData.filter(book => book.STATUS === '已售出').length;

        // 获取推荐书籍
        const recommendedResponse = await axios.get('http://localhost:3000/api/recommended-books');
        this.recommendedBooks = recommendedResponse.data.recommendedBooks;
      } catch (error) {
        console.error('Error fetching books:', error);
        this.$message.error('获取书籍数据失败，请稍后重试');
      }
    },
    // 搜索书籍
    handleSearch() {
      this.fetchBooks();
    },
    // 分页大小改变
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchBooks();
    },
    // 当前页改变
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchBooks();
    },
    // 编辑书籍
    handleEdit(row) {
      console.log('编辑书籍：', row);
    },
    // 删除书籍
    handleDelete(row) {
      console.log('删除书籍：', row);
      this.operationLogs.push({ action: '删除', bookName: row.BookName, time: new Date().toLocaleString() });
    },
    // 上传书籍
    async handleUpload() {
      try {
        await axios.post('http://localhost:3000/api/upload-book', this.bookForm); // 调用上传书籍接口
        this.$message.success('书籍上传成功');
        this.operationLogs.push({
          action: '上传',
          bookName: this.bookForm.BookName,
          time: new Date().toLocaleString(),
        });
        this.dialogVisible = false;
        this.fetchBooks(); // 刷新书籍列表
      } catch (error) {
        console.error('Error uploading book:', error);
        this.$message.error('书籍上传失败，请稍后重试');
      }
    },
    // 点击行查看详情
    handleRowClick(row) {
      this.selectedBook = { ...row }; // 深拷贝，避免直接修改原数据
      this.detailDialogVisible = true;
    },
    // 更改状态
    handleStatusChange(row) {
      console.log('更改状态：', row);
      this.operationLogs.push({ action: '更改状态', bookName: row.BookName, time: new Date().toLocaleString() });
    },
    // 下架书籍
    async handleOffShelf(book) {
      try {
        await axios.delete(`http://localhost:3000/api/books/remove/${book.id}`);
        this.$message.success('书籍已下架');
        this.operationLogs.push({
          action: '下架',
          bookName: book.BookName,
          time: new Date().toLocaleString(),
        });
        this.fetchBooks(); // 刷新书籍列表
      } catch (error) {
        console.error('Error deleting book:', error);
        this.$message.error('下架失败，请稍后重试');
      }
    },
    // 更改价格
    async handleChangePrice(book) {
      const newPrice = await this.$prompt('请输入新的价格', '更改价格', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d+(\.\d{1,2})?$/, // 验证输入为数字
        inputErrorMessage: '价格格式不正确',
      });

      if (newPrice) {
        // 将 newPrice 转换为数字类型
        book.price = parseFloat(newPrice.value);

        try {
          await axios.put(`http://localhost:3000/api/books/update/${book.id}`, book);
          this.$message.success('价格已更新');
          this.operationLogs.push({
            action: '更改价格',
            bookName: book.BookName,
            time: new Date().toLocaleString(),
          });
          this.fetchBooks(); // 刷新书籍列表
        } catch (error) {
          console.error('Error updating price:', error);
          this.$message.error('价格更新失败，请稍后重试');
        }
      }
    },
    // 保存书籍修改
    async saveBookChanges() {
      try {
        // 确保 price 是数字类型
        this.selectedBook.price = parseFloat(this.selectedBook.price);

        // 确保 STATUS 是合法值
        if (!['可售', '已售出'].includes(this.selectedBook.STATUS)) {
          return this.$message.error('状态值不合法');
        }

        // 发送 PUT 请求
        await axios.put(`http://localhost:3000/api/books/update/${this.selectedBook.id}`, this.selectedBook);

        this.$message.success('书籍信息已保存');
        this.operationLogs.push({
          action: '保存',
          bookName: this.selectedBook.BookName,
          time: new Date().toLocaleString(),
        });
        this.detailDialogVisible = false; // 关闭弹窗
        this.fetchBooks(); // 刷新书籍列表
      } catch (error) {
        console.error('Error saving book changes:', error);
        this.$message.error('保存失败，请稍后重试');
      }
    },

    async recommendBook() {
      try {
        const response = await axios.post('http://localhost:3000/api/recommend-book', {
          bookId: this.selectedBook.id, // 传递书籍 ID
        });

        if (response.data.success) {
          this.$message.success('书籍已推荐');
          this.operationLogs.push({
            action: '推荐',
            bookName: this.selectedBook.BookName,
            time: new Date().toLocaleString(),
          });
        }
      } catch (error) {
        console.error('Error recommending book:', error);
        this.$message.error('推荐失败，请稍后重试');
      }
    },
    // 表格行样式
    tableRowClassName({ row }) {
      if (row.STATUS === '已售出') {
        return 'sold-row';
      }
      return '';
    }
  },
  mounted() {
    this.fetchBooks();
  }
};
</script>

<style scoped>
.el-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  font-weight: bold;
}

.el-table {
  margin-top: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.el-table__header th {
  background-color: #f5f7fa;
  color: #333;
  font-weight: bold;
}

.el-table__body tr:hover {
  background-color: #f0f9eb;
}

.el-table__body tr.sold-row {
  background-color: #fde2e2;
}

.el-pagination {
  margin-top: 20px;
}

.el-dialog__body {
  padding: 20px;
}

.el-tag {
  font-size: 14px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-label {
  font-size: 16px;
  color: #666;
}

.stat-value {
  font-size: 20px;
  color: #333;
  font-weight: bold;
}
</style>